import React, {PropTypes, Component} from 'react';
import reqwest from 'reqwest';

import {Icon, Form, Upload,message,Input} from 'antd';
import API,{OSS_UPLOAD} from "../../lib/api";
import {handlerPic} from "../../lib/utils";

const Dragger = Upload.Dragger;
const FormItem = Form.Item;

import './style.less';



export default class OssUpload extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            fileList: [],
            files : []
        }
    }




    componentWillReceiveProps(nextProps){

        let fileList = nextProps.default;
        let list = [],
            files = [];

        if(fileList){
            fileList.split(',').map((v,k)=> {
                list.push({
                    uid:k+1,
                    name: v,
                    status: 'done',
                    url: handlerPic(v,1500),
                    thumbUrl: handlerPic(v,400),
                    fullname:v,
                })
                files.push(v);
            })
            this.setState({
                fileList:list,
                files:files
            })
        }
    }

    removePic(file){
        const {fileList,files} = this.state;

        fileList.map((v,k) => {
            if(file.uid == v.uid){
                fileList.splice(k,1);
            }

            if(files.indexOf(file.fullname) > -1){
                files.splice(files.indexOf(file.fullname),1);
            }

            v.uid = k+1;

        })

        this.setState({
            fileList:fileList,
            files:files
        })

        let field = files.join(',');

        this.props.onFieldSet && this.props.onFieldSet(field);
    }

    beforeUpload(file) {
        const {fileList} = this.state;
        console.log(fileList);
        if(this.props.multiple && fileList.length >= 5){
            message.error('最多可上传五张图片');
            return;
        }

        this.handleUpload(file);
        return false;
    }


    handleUpload(file) {

        const formData = new FormData();


        const _this = this;


        API.fetch(OSS_UPLOAD,{},resp=> {
            let suffix = _this.get_suffix(file.name),
                filename  = _this.random_string(10) + suffix,
                fullname = resp.dir + filename,
                field;

            formData.append('key',fullname);
            formData.append('policy',resp.policy);
            formData.append('OSSAccessKeyId',resp.accessid);
            formData.append('success_action_status','200');
            formData.append('signature',resp.signature);
            formData.append('file', file);
            reqwest({
                url: resp.host,
                method: 'post',
                processData:false,
                data:formData,
                success: () => {
                    let {fileList,files} = this.state;
                    if(fileList.length >= 5){
                        message.error('最多可上传五张图片')
                        return;
                    }

                    if(_this.props.multiple){
                        fileList.push( {
                            uid:fileList.length + 1,
                            name: fullname,
                            status: 'done',
                            url: handlerPic(fullname,1500),
                            thumbUrl: handlerPic(fullname,400),
                            fullname:fullname,
                        })
                        files.push(fullname);
                        // _this.setState({
                        //     fileList:fileList,
                        //     files:files
                        // })
                        field = files.join(',');
                        console.log(field);
                    }else{
                        let newList = [],
                            newfiles = [];
                        newList.push( {
                            uid: fileList.length + 1,
                            name: fullname,
                            status: 'done',
                            url: handlerPic(fullname,1500),
                            thumbUrl: handlerPic(fullname,400),
                            fullname:fullname,
                        })

                        newfiles.push(fullname);
                        // _this.setState({
                        //     fileList:newList,
                        //     files:files
                        // })
                        field = fullname;
                    }

                    _this.props.onFieldSet && _this.props.onFieldSet(field);

                },
                error: () => {
                    message.error(file.name + '上传失败');
                },
            });
        })
    }


    get_suffix(filename) {
        let pos = filename.lastIndexOf('.'),
            suffix = '';
        if (pos != -1) {
            suffix = filename.substring(pos)
        }
        return suffix;
    }

    random_string(len) {
        len = len || 32;
        let chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678',
            maxPos = chars.length,
            pwd = '';
        for (let i = 0; i < len; i++) {
            pwd += chars.charAt(Math.floor(Math.random() * maxPos));
        }
        return pwd;
    }

    render() {



        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 4},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 16},
            },
        };



        return (
            <div>
                {/*  需要配置 标题 required星号  */}
                <FormItem
                    {...formItemLayout}
                    label={this.props.lable}
                    hasFeedback
                    required={true}

                >
                    <div style={{marginTop: 16, height: 180}}>
                        <Dragger
                            multiple={false}
                            showUploadList={true}
                            beforeUpload={this.beforeUpload.bind(this)}
                            onRemove={this.removePic.bind(this)}
                            fileList={this.state.fileList}
                            listType="picture"
                            className="upload-list-inline"
                        >
                            <p className="ant-upload-drag-icon"><Icon type="inbox"/></p>
                            <p className="ant-upload-text">点击或拖动文件进行上传</p>
                            <p className="ant-upload-hint">支持单个或批量上传</p>
                            {
                                //dimension 建议大小 [w,h]
                                this.props.dimension?
                                    <div>建议大小为{this.props.dimension[0]}x{this.props.dimension[1]}</div>
                                    :null
                            }
                        </Dragger>

                    </div>
                </FormItem>


            </div>


        )
    }

}